<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="栏目名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入栏目名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="权限" prop="role">
        <el-input
          v-model="queryParams.role"
          placeholder="请输入权限"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['conlumn:conlumn:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['conlumn:conlumn:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['conlumn:conlumn:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['conlumn:conlumn:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="conlumnList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="网站栏目id" align="center" prop="id" />
      <el-table-column label="网站栏目名称" align="center" prop="name" />
      <el-table-column label="权限" align="center" prop="role" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['conlumn:conlumn:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['conlumn:conlumn:remove']"
          >删除</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-setting"
            @click="handlePermission(scope.row)"
          >权限</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    /> -->

    <!-- 添加或修改栏目管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="网站栏目名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入网站栏目名称" />
        </el-form-item>
        <el-form-item label="权限" prop="role">
          <el-input v-model="form.role" placeholder="请输入权限" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 栏目权限设置对话框 -->
    <el-dialog :title="'栏目权限设置 - ' + permissionForm.columnName" :visible.sync="permissionOpen" width="600px" append-to-body>
      <!-- 加载状态 -->
      <div v-loading="permissionLoading" element-loading-text="加载中..." style="min-height: 200px;">
        <el-table :data="deptList" style="width: 100%" v-if="!permissionLoading">
          <el-table-column prop="deptName" label="分局名称" width="200"></el-table-column>
          <el-table-column label="操作" width="120">
            <template slot-scope="scope">
              <!-- 权限开关 -->
              <el-switch
                v-model="scope.row.hasPermission"
                active-color="#13ce66"
                inactive-color="#ff4949"
                @change="handlePermissionChange(scope.row)">
              </el-switch>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="permissionOpen = false">关 闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listConlumn, getConlumn, delConlumn, addConlumn, updateConlumn } from "@/api/conlumn/conlumn";
import { getDepts, addColumnPermission, delColumnPermission, checkColumnPermission, listColumnPermission, checkDeptPermission } from "@/api/conlumn/permission";

export default {
  name: "Conlumn",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 栏目管理表格数据
      conlumnList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 权限弹出层是否显示
      permissionOpen: false,
      // 权限弹出层加载状态
      permissionLoading: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        role: null
      },
      // 表单参数
      form: {},
      // 权限表单参数
      permissionForm: {
        columnId: null,
        columnName: null
      },
      // 分局列表
      deptList: [],
      // 已分配权限的分局列表
      assignedPermissions: [],
      // 表单校验
      rules: {
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询栏目管理列表 */
    getList() {
      this.loading = true;
      listConlumn(this.queryParams).then(response => {
        this.conlumnList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 权限设置按钮操作
    handlePermission(row) {
      this.permissionForm.columnId = row.id;
      this.permissionForm.columnName = row.name;
      // 先设置加载状态，避免权限开关跳动
      this.deptList = [];
      this.permissionLoading = true;
      this.permissionOpen = true;
      this.getDepts().then(() => {
        return this.getAssignedPermissions();
      }).then(() => {
        // 数据加载完成，关闭加载状态
        this.permissionLoading = false;
      }).catch(() => {
        // 出现错误也关闭加载状态
        this.permissionLoading = false;
      });
    },
    // 获取所有分局列表
    getDepts() {
      return getDepts().then(response => {
        this.deptList = response.data.map(dept => ({
          ...dept,
          hasPermission: false // 默认无权限，实际权限会在getAssignedPermissions中设置
        }));
        return Promise.resolve();
      });
      //console.log(this.deptList);
    },
    // 获取已分配的权限列表
    getAssignedPermissions() {
      // 创建一个包含所有权限检查的Promise数组
      const permissionPromises = this.deptList.map(dept => {
        return checkDeptPermission(this.permissionForm.columnId, dept.deptId).then(response => {
          this.$set(dept, 'hasPermission', response.data);
        });
      });

      // 等待所有权限检查完成并返回Promise
      return Promise.all(permissionPromises).then(() => {
        console.log('所有权限检查完成', this.deptList);
      }).catch(error => {
        console.error('权限检查出错', error);
        throw error;
      });
    },
    // 获取当前栏目的role
    getCurrentColumnRole() {
      const column = this.conlumnList.find(item => item.id === this.permissionForm.columnId);
      return column ? column.role : null;
    },
    // 处理权限变更
    handlePermissionChange(row) {
      const originalState = row.hasPermission; // 保存原始状态，用于操作失败回滚
      const currentColumnRole = this.getCurrentColumnRole();

      // 对于role为1的栏目，处理逻辑不同
      if (currentColumnRole === '1') {
        if (!row.hasPermission) {
          // 关闭权限开关 - 为role为1的栏目添加移除权限的记录
          const permissionData = {
            columnId: this.permissionForm.columnId,
            deptId: row.deptId,
            deptName: row.deptName,
            permissionType: 2 // 2表示移除权限
          };
          addColumnPermission(permissionData)
            .then(() => {
              this.$modal.msgSuccess("权限移除成功");
              // 重新加载权限状态
              setTimeout(() => {
                this.getAssignedPermissions();
              }, 500);
            })
            .catch(() => {
              row.hasPermission = originalState; // 回滚状态
              this.$modal.msgError("权限移除失败");
            });
        } else {
          // 打开权限开关 - 删除role为1的栏目移除权限的记录
          const columnId = parseInt(this.permissionForm.columnId, 10);
          const deptId = parseInt(row.deptId, 10);
          checkColumnPermission(columnId, deptId)
            .then(response => {
              console.log("检查等待删除的权限数据:"+response.data);
              if (response.data) {
                delColumnPermission(response.data.id)
                  .then(() => {
                    this.$modal.msgSuccess("权限恢复成功");
                    // 重新加载权限状态
                    setTimeout(() => {
                      this.getAssignedPermissions();
                    }, 500);
                  })
                  .catch(() => {
                    row.hasPermission = originalState; // 回滚状态
                    this.$modal.msgError("权限恢复失败");
                  });
              } else {
                // 如果没有找到权限记录，说明权限已经被移除了
                this.$modal.msgSuccess("权限恢复成功");
              }
            })
            .catch(() => {
              console.log("恢复权限时row数据"+row.deptId);
              row.hasPermission = originalState; // 回滚状态
            });
        }
      } else {
        // 对于其他role的栏目，使用原有逻辑
        // 打开权限开关
        if (row.hasPermission) {
          const permissionData = {
            columnId: this.permissionForm.columnId,
            deptId: row.deptId,
            deptName: row.deptName,
            permissionType: 1 // 1表示添加权限
          };
          addColumnPermission(permissionData)
            .then(() => {
              this.$modal.msgSuccess("权限分配成功");
              // 重新加载权限状态
              setTimeout(() => {
                this.getAssignedPermissions();
              }, 500);
            })
            .catch(() => {
              row.hasPermission = originalState; // 回滚状态
              this.$modal.msgError("权限分配失败");
            });
        } else {
          // 确保参数为 int 类型
          const columnId = parseInt(this.permissionForm.columnId, 10);
          // 关闭权限开关
          const deptId = parseInt(row.deptId, 10);
          checkColumnPermission(columnId, deptId)
            .then(response => {

              console.log("检查等待删除的权限数据:"+response.data);

              if (response.data) {
                delColumnPermission(response.data.id)
                  .then(() => {
                    this.$modal.msgSuccess("权限移除成功");
                    // 重新加载权限状态
                    setTimeout(() => {
                      this.getAssignedPermissions();
                    }, 500);
                  })
                  .catch(() => {
                    row.hasPermission = originalState; // 回滚状态
                    this.$modal.msgError("权限移除失败");
                  });
              } else {
                // 如果没有找到权限记录，说明权限已经被移除了
                this.$modal.msgSuccess("权限移除成功");
              }
            })
            .catch(() => {
              console.log("关闭权限开关时row数据"+row.deptId);
              row.hasPermission = originalState; // 回滚状态
            });
        }
      }
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        name: null,
        role: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加栏目管理";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getConlumn(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改栏目管理";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateConlumn(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addConlumn(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除栏目管理编号为"' + ids + '"的数据项？').then(function() {
        return delConlumn(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('conlumn/conlumn/export', {
        ...this.queryParams
      }, `conlumn_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
